package com.app.store.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.app.store.dao.StoreDao;
import com.app.store.dto.AppVersionDto;
import com.app.store.model.AppVersion;
import com.app.store.service.StoreService;
import com.app.sysmodule.exception.ServiceException;
import com.app.sysmodule.utils.PropertyUtils;
import io.netty.bootstrap.Bootstrap;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by song on 2017/11/28.
 */
public class StoreServiceImpl implements StoreService {
    private static Logger log = Logger.getLogger(StoreServiceImpl.class);
    @Autowired
    private StoreDao storeDao;
//    public Map<String, Object> getDownLoan(String version) throws ServiceException {
//        Map<String,Object> map = new HashMap<String, Object>();
//        if(StringUtils.isNotEmpty(version)){
//            //根据当前服务端版本查询当前app版本号
//            try{
//                AppVersion ver = storeDao.getVersion(version);
//                if(null != ver){
//                    AppVersionDto dto = new AppVersionDto();
//                    dto.setId(ver.getId());
//                    dto.setAppName(ver.getAppName());
//                    dto.setServerVersion(ver.getServerVersion());
//                    dto.setAppVersion(ver.getAppVersion());
//                    dto.setIsUpgrade(ver.getIsUpgrade());
//                    dto.setCreateDate(ver.getCreateDate());
//                    String downloanUrl = PropertyUtils.getProperty("download_url");
//                    String url = downloanUrl + ver.getAppVersion()+"/download.jsp";
//                    dto.setUrl(url);
//                    map.put("appVersionDto",dto);
//                }
//            }catch (Exception e){
//               throw new ServiceException(e.getMessage());
//            }
//        }
//        return map;
//    }

    public AppVersionDto downInfo(String version, String type ,String source) throws ServiceException {
        AppVersionDto dto = new AppVersionDto();
        try {
            AppVersion ver = storeDao.getVersion1(version,type,source);
            if(null != ver){
                dto.setId(ver.getId());
                dto.setAppName(ver.getAppName());
                dto.setServerVersion(ver.getServerVersion());
                dto.setAppVersion(ver.getAppVersion());
                dto.setIsUpgrade(ver.getIsUpgrade());
                dto.setCreateDate(ver.getCreateDate());
                dto.setType(ver.getType());
                dto.setSource(ver.getSource());
                dto.setIsDelete(ver.getIsDelete());
                dto.setUpdateDate(ver.getUpdateDate());
                dto.setRemark(ver.getRemark());
                dto.setSize(ver.getSize());
//                String downloanUrl = PropertyUtils.getProperty("download_url");
//                String appStoreUrl = PropertyUtils.getProperty("app_store_url");
//                String url = null;
                //测试环境
//                if("01".equals(type)){
//                   url = appStoreUrl + downloanUrl +"app-download/"+ver.getAppVersion()+"/manifest.plist";
//                }else {
//                    url = downloanUrl +"app-download/"+ver.getAppVersion()+"/yiqi-android.apk";
//                }
                dto.setUrl(ver.getUrl());
            }
        }catch(Exception e){
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
        return dto;
    }

    /**
     * 判断app版本号是否需要更新
     * 初始设计数据库有问题  做一次数据转换
     * @param type
     * @param appVersion
     * @param serverVersion
     * @return
     */
    public AppVersionDto getVersion(String type, String appVersion, String serverVersion) throws ServiceException {
        String source = "scm";
        AppVersionDto dto = new AppVersionDto();
        try{
            AppVersion ver = storeDao.getVersion1(serverVersion,type,source);
            if(null != ver && null != ver.getAppVersion()){
                String nowVersion = ver.getAppVersion();
                boolean flag = compareStr(nowVersion,appVersion);
                if(flag){
                    //获取最后一次强制更新版本
                    AppVersion ver1 = storeDao.getVersion2(serverVersion,type,source);
                    if(null != ver1 && null != ver1.getAppVersion() && compareStr(ver1.getAppVersion(),appVersion)){
                        ver.setIsUpgrade(1L);
                    }
                    if(null != ver){
                        dto.setId(ver.getId());
                        dto.setAppName(ver.getAppName());
                        dto.setServerVersion(ver.getServerVersion());
                        dto.setAppVersion(ver.getAppVersion());
                        dto.setIsUpgrade(ver.getIsUpgrade());
                        dto.setCreateDate(ver.getCreateDate());
                        dto.setType(ver.getType());
                        dto.setSource(ver.getSource());
                        dto.setIsDelete(ver.getIsDelete());
                        dto.setUpdateDate(ver.getUpdateDate());
                        dto.setRemark(ver.getRemark());
                        dto.setSize(ver.getSize());
                        String downloanUrl = PropertyUtils.getProperty("download_url");
                        String appStoreUrl = PropertyUtils.getProperty("app_store_url");
                        String url = null;
                        if("01".equals(type)){
                            url = downloanUrl+"homePage.jsp?version=V"+serverVersion+"&source="+source;
                            dto.setUrl(url);
                        }else {
//                            url = downloanUrl +"app-download/"+ver.getAppVersion()+"/yiqi-android.apk";
                            dto.setUrl(ver.getUrl());
                        }
                    }
                    return dto;
                }
            }
        }catch (Exception e){
            throw  new ServiceException();
        }
        return null;
    }

    public Boolean saveAppVersion(String version, String type, String fileSize, String fileName,String isUpgrade,String serverVersion,String remark,String downFileUrl,String username) throws ServiceException {
        Boolean flag = false;
        try{
            AppVersion appVersion = storeDao.findVersionByTypeAndVersion(type,version);
            if(null == appVersion){
                AppVersion appVersion1 = new AppVersion();
                appVersion1.setIsUpgrade(Long.parseLong(isUpgrade));
                appVersion1.setUpdateDate(new Date());
                appVersion1.setCreateDate(new Date());
                appVersion1.setAppName(fileName);
                appVersion1.setAppVersion(version);
                appVersion1.setSize(fileSize);
                appVersion1.setUrl(downFileUrl);
                if(serverVersion.toLowerCase().contains("v")){
                    appVersion1.setServerVersion(serverVersion.substring(1,serverVersion.length()));
                }else {
                    appVersion1.setServerVersion(serverVersion);
                }
                appVersion1.setIsDelete(0l);
                appVersion1.setSource("scm");
                appVersion1.setRemark(remark);
                appVersion1.setType(type);
                appVersion1.setUsername(username);
                storeDao.save(appVersion1);
                flag = true;
            }
            return flag;
        }catch (Exception e){
            throw new ServiceException(e.getMessage());
        }
    }

    @Override
    public AppVersion getNewByType(String type,String source) throws ServiceException {
        try{
            AppVersion appVersion = storeDao.getVersionByType(type,source);
            if(null != appVersion){
                return appVersion;
            }
        }catch (Exception e){
            throw new ServiceException(e.getMessage());
        }
        return null;
    }

    @Override
    public void deleteOss(String endpoint, String accessKeyId, String accessKeySecret,String bucketName, String serverVersion, String type, Integer size) throws ServiceException {
        try {
            log.info("删除多余安装包  ------bucketName："+bucketName+"---- serverVersion："+serverVersion+"------ type:"+type);
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            List<AppVersion> list = storeDao.getDeleteInfo(serverVersion, type, size);
            if (null != list && list.size() > 0) {
                String packetName = null;
                String bucketKey = null;
                List<Long> idList = new ArrayList<Long>();
                if ("01".equals(type)) {
                    packetName = "CRM_YUN.ipa";
                } else if ("02".equals(type)) {
                    packetName = "yiqi-android.apk";
                }
                for (AppVersion appVersion : list) {
                    bucketKey = appVersion.getAppVersion() + "/" + packetName;
                    boolean exists = ossClient.doesObjectExist(bucketName, bucketKey);
                    log.info("deleteOss bucketName:" + bucketName+"------bucketKey:"+bucketKey);
                    if (exists) {
                        ossClient.deleteObject(bucketName, bucketKey);
                    }
                    idList.add(appVersion.getId());
                }
                if (null != idList && idList.size() > 0) {
                    storeDao.batchDelete(idList);//删除数据库
                }
            }
            ossClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



    public String generatePlistFile(String packageName, String version, String packagerUrl,String downLoadPath) throws ServiceException {
        String dirName = null;
        String plist = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                + "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
                + "<plist version=\"1.0\">\n" + "<dict>\n"
                + "<key>items</key>\n"
                + "<array>\n"
                + "<dict>\n"
                + "<key>assets</key>\n"
                + "<array>\n"
                + "<dict>\n"
                + "<key>kind</key>\n"
                + "<string>software-package</string>\n"
                + "<key>url</key>\n"
                //你之前所上传的ipa文件路径
                + "<string>"+packagerUrl+"</string>\n"
                + "</dict>\n"
                + "</array>\n"
                + "<key>metadata</key>\n"
                + "<dict>\n"
                + "<key>bundle-identifier</key>\n"
                //这个是开发者账号用户名，也可以为空，为空安装时看不到图标，完成之后可以看到
                + "<string>"+packageName+"</string>\n"
                + "<key>bundle-version</key>\n"
                + "<string>"+version+"</string>\n"
                + "<key>kind</key>\n"
                + "<string>software</string>\n"
                + "<key>title</key>\n"
                + "<string>易企</string>\n"
                + "</dict>\n"
                + "</dict>\n"
                + "</array>\n"
                + "</dict>\n"
                + "</plist>";
        try{
            dirName =downLoadPath+"/"+version+"/";//目录
            String fileName = dirName+"manifest.plist";//文件
            File catalogueFile = new File(dirName);
            if (!catalogueFile.exists()) {
                catalogueFile.mkdirs();//创建目录
             }
            File plistFile = new File(fileName);
            if(!plistFile.exists()){
                plistFile.createNewFile(); // 创建新文件
                BufferedWriter out = new BufferedWriter(new FileWriter(plistFile));
                out.write(plist); // \r\n即为换行
                out.flush(); // 把缓存区内容压入文件
                out.close(); // 最后记得关闭文件
            }else {
                log.error(fileName+"---文件已经存在");
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        return dirName;
    }
    /**
     * 比较版本大小
     * oldVersion 数据库版本
     * newVersion 客户端传递版本
     */
    private boolean compareStr(String oldVersion, String newVersion) {
        boolean flag = false;
        String oStr[] = oldVersion.split("\\.");
        String vStr[] = newVersion.split("\\.");
        for(int i=0;i<oStr.length;i++){
            if(Integer.parseInt(oStr[i])>Integer.parseInt(vStr[i])){
                flag = true;
                break;
            }else if(Integer.parseInt(oStr[i])<Integer.parseInt(vStr[i])){
                flag = false;
                break;
            }
        }
        return flag;
    }
    @Override
    public List<String> getServerVersionList(String source) throws ServiceException{
        try{
            List<String> list = storeDao.getServerVersionList(source);
            if(list != null && list.size()>0){
                List<String> li = new ArrayList<String>();
                for(String str  :list){
                   li.add("V"+str);
                }
                return li;
            }
            return null;
        }catch (Exception e){
            throw new ServiceException(e.getMessage());
        }
    }
}
